package com.xl.studentpass.utils;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author xxl
 */
public class ThreadPoolUtils {

    static String threadName;

    private static final class ThreadPoolExecutorHolder {
        static final ThreadPoolExecutor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(6,
                12,
                1L,
                TimeUnit.MINUTES,
                new LinkedBlockingDeque<>(), new NameThreadFactory(threadName));
    }

    public static ThreadPoolExecutor getThreadPool(String name) {
        threadName = name;
        return ThreadPoolExecutorHolder.THREAD_POOL_EXECUTOR;
    }
}

/**
 * 自定义类实现线程工厂类已实现传入指定参数给线程命名
 */
class NameThreadFactory implements ThreadFactory {
    private final String namePrefix;
    private final ThreadGroup threadGroup;

    private final AtomicInteger threadNumber = new AtomicInteger(1);

    NameThreadFactory(String name) {
        SecurityManager s = System.getSecurityManager();
        threadGroup = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
        if (null == name || "".equals(name.trim())) {
            name = "pool";
        }
        AtomicInteger poolNumber = new AtomicInteger(1);
        namePrefix = name + "-" +
                poolNumber.getAndIncrement() +
                "-thread-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(threadGroup, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}
